package com.yihong.userserver.controller;

import com.yihong.common.util.AjaxJson;
import com.yihong.common.util.AjaxJsonFactory;
import com.yihong.common.util.JwtUtil;
import com.yihong.userserver.entity.User;
import com.yihong.userserver.enums.StatusEnum;
import com.yihong.userserver.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName LoginController
 * @Description TODO
 * @Author 孟志浩
 * @Date 2019/3/19 15:16
 **/
@RestController
public class LoginController {

    @Value("${login.keepTime}")
    private Long keepTime;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/login")
    public AjaxJson login(@RequestBody User user){
        user = userRepository.findUserByLoginNameAndPasswordAndIsValidEquals(user.getLoginName(), user.getPassword(),StatusEnum.ENABLE.getCode());
        if (user == null) {
            return AjaxJsonFactory.createAjaxJson(401, "登录失败，用户名密码错误");
        }
        user.setRoleList(null);
        user.setLastLoginTime(new Date());
        userRepository.saveAndFlush(user);
        Map<String, Object> jwtEntry = new HashMap<>();
        jwtEntry.put("userId", user.getId());
        String tokenKey = JwtUtil.createJWT(jwtEntry);
        redisTemplate.opsForValue().set(tokenKey, "p", keepTime, TimeUnit.SECONDS);
        Map m = new HashMap(2);
        m.put("Authorization", tokenKey);
        m.put("userInfo", user.setPassword(null));
        return AjaxJsonFactory.createOnlyData(m);
    }

}
